#!/usr/bin/env python
# -*- coding:utf-8 -*-

import argparse

from fabric.api import *
from fabric.contrib.files import exists

BASE_PATH = '/usr/app/python/'
TAR_FILE = 'crawler-api.tar.gz'
APP_PATH = BASE_PATH + 'crawler-api'
APP_NAME = 'crawler_api.py'


def tar_codes():
    with settings(warn_only=True):
        # local("virtualenv sc_env && source sc_env/bin/activate && pip install -r requirements.txt", shell='/bin/bash')
        local("rm */*.pyc", shell='/bin/bash')
        local("tar -zcf {fname} *".format(fname=TAR_FILE), shell='/bin/bash')


def deploy_app():
    if not exists(APP_PATH):
        run('mkdir -p ' + APP_PATH)
    with settings(warn_only=True):
        sudo('rm -Rf ' + APP_PATH + '/*')
    put(TAR_FILE, APP_PATH + '/')
    with cd(APP_PATH):
        run('tar -zxf ' + TAR_FILE, shell='/bin/bash')
        run('rm ' + TAR_FILE, shell='/bin/bash')


def run_app():
    with settings(warn_only=True):
        sudo('pkill -f ' + APP_NAME)
    with cd(APP_PATH):
        run('sleep 2')
        run('source sc_env/bin/activate && $(nohup python {app} >& /dev/null < /dev/null &) && sleep 1'.format(
            app=APP_NAME), shell='/bin/bash')


def kill():
    with settings(warn_only=True):
        run('pkill -f ' + APP_NAME)

@parallel(pool_size=4)
def install_package():
    # sudo('apt-get -y update')
    sudo('apt-get -y install libpq-dev')
    sudo('pip install psycopg2')



@parallel(pool_size=10)
def test():
    run('pip list | grep xtls')


if __name__ == "__main__":
    """ deploy test ,

    just push file
    test path : /usr/app/python/crawler-api-test
    """
    env.hosts = [
        "xu.du@120.26.93.104",
        #"xu.du@121.43.150.81",
        #"xu.du@115.29.198.28",
        #"xu.du@120.26.93.125",
        #"xu.du@120.26.93.104",
    ]
    env.password = 'Sunday.2016'
    tar_codes()
    APP_PATH = APP_PATH + '-test'
    execute(deploy_app)
    #execute(install_package)

